package com.kkb.mybatis.test.mybatis;

import com.kkb.mybatis.po.User;
import org.apache.commons.dbcp.BasicDataSource;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.*;

public class MybatisV1 {

    private Properties properties = new Properties();

    @Test
    public void test() {
        loadProperties("jdbc.properties");
        Map<String, Object> map = new HashMap();
        map.put("name", "小明");
        map.put("gender", "男");
        List<User> users = selectList("queryUserByParams", map);
        System.out.println(users);
    }

    private void loadProperties(String location) {
        //加载配置文件
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(location);
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private <T> List<T> selectList(String statementId, Object param) {

        List<T> results = new ArrayList();
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(properties.getProperty("db.driver"));
            dataSource.setUrl(properties.getProperty("db.url"));
            dataSource.setUsername(properties.getProperty("db.username"));
            dataSource.setPassword(properties.getProperty("db.password"));

            conn = dataSource.getConnection();
           /* //获取驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            //获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/kaike?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8","root","123456");*/

            String sql = properties.getProperty("db.sql." + statementId);
            preparedStatement = conn.prepareStatement(sql);
            //preparedStatement.setObject(1, id);
            if (param instanceof Integer || param instanceof String) {
                preparedStatement.setObject(1, param);
            } else if (param instanceof Map) {
                Map<String, Object> objectMap = (Map<String, Object>) param;

                String columnnames = properties.getProperty("db.sql." + statementId + ".columnnames");
                String[] names = columnnames.split(",");

                if (names != null && names.length > 0) {
                    for (int i = 0; i < names.length; i++) {
                        String name = names[i];
                        Object value = objectMap.get(name);
                        preparedStatement.setObject(i + 1, value);
                    }
                }

            }

            resultSet = preparedStatement.executeQuery();

            String resultType = properties.getProperty("db.sql." + statementId + ".resultclassname");
            Class<?> classzz = Class.forName(resultType);
            Object result = null;
            while (resultSet.next()) {
                result = classzz.newInstance();
                ResultSetMetaData metaData = resultSet.getMetaData();
                int columnCount = metaData.getColumnCount();
                for (int i = 0; i < columnCount; i++) {
                    String columnName = metaData.getColumnName(i + 1);
                    Field field = classzz.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(result, resultSet.getObject(columnName));
                }
                results.add((T) result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return results;
    }
}
